<section class="<%= typeof sectionClass !== 'undefined' ? sectionClass : '' %>">
    <div class="mx-auto max-w-2xl px-4 py-16 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8">
        <div class="flex justify-between items-center mb-8">
            <h2 class="text-2xl font-bold tracking-tight text-gray-900"><%= sectionTitle %></h2>
            <a href="<%= viewMoreLink %>" class="text-sm font-medium text-blue-600 hover:text-blue-500"><%= viewMoreText %></a>
        </div>

        <div class="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-4 xl:gap-x-8">
            <% products.forEach(function(product) { %>
                <div class="group relative bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 p-4">
                    <div class="product-link cursor-pointer" data-href="/product/<%= product.id %>">
                        <div class="aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-md bg-gray-100 group-hover:opacity-75 transition duration-300">
                            <img src="<%= product.mainPic %>" 
                                 alt="<%= product.title %>"
                                 class="h-full w-full object-cover object-center">
                            <% if (product.discount) { %>
                                <div class="absolute top-2 right-2 bg-red-500 text-white text-sm px-2 py-1 rounded">
                                    -<%= product.discount %>%
                                </div>
                            <% } %>
                        </div>
                        <div class="mt-4 space-y-3">
                            <h3 class="text-sm text-gray-700">
                                <%= product.title %>
                            </h3>
                            <div class="flex items-center">
                                <p class="text-lg font-medium text-gray-900">¥<%= product.price %></p>
                                <% if (product.originalPrice) { %>
                                    <p class="ml-2 text-sm text-gray-500 line-through">¥<%= product.originalPrice %></p>
                                <% } %>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 flex items-center space-x-2">
                        <div class="flex items-center border rounded-md">
                            <button 
                                type="button"
                                class="px-2 py-1 text-gray-600 hover:bg-gray-100 rounded-l-md border-r"
                                onclick="decreaseQuantity(event, '<%= product.id %>')"
                            >-</button>
                            <input 
                                type="number" 
                                id="quantity-<%= product.id %>"
                                class="w-14 px-2 py-1 text-center focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                                value="1"
                                min="1"
                                max="99"
                                onchange="validateQuantity(this, event)"
                                onkeyup="validateQuantity(this, event)"
                            >
                            <button 
                                type="button"
                                class="px-2 py-1 text-gray-600 hover:bg-gray-100 rounded-r-md border-l"
                                onclick="increaseQuantity(event, '<%= product.id %>')"
                            >+</button>
                        </div>
                        <button 
                            type="button"
                            onclick="addToCart(event, '<%= product.id %>')"
                            class="flex-1 bg-blue-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors duration-200"
                        >
                            加入购物车
                        </button>
                    </div>
                </div>
            <% }); %>
        </div>
    </div>

    <!-- 提示消息 -->
    <div id="toast" class="fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg transform transition-transform duration-300 translate-y-[-100%] opacity-0">
    </div>
</section>

<script>
    // 为所有商品链接添加点击事件
    document.addEventListener('DOMContentLoaded', function() {
        const productLinks = document.querySelectorAll('.product-link');
        productLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                // 检查点击事件是否来自控制区域
                const controls = e.target.closest('.mt-4');
                if (!controls) {
                    window.location.href = this.dataset.href;
                }
            });
        });
    });

    // 获取购物车数据
    function getCartItems() {
        const cart = localStorage.getItem('shopCart');
        return cart ? JSON.parse(cart) : [];
    }

    // 保存购物车数据
    function saveCartItems(items) {
        localStorage.setItem('shopCart', JSON.stringify(items));
    }

    // 更新header中的购物车数量
    function updateHeaderCartCount() {
        const cartItems = getCartItems();
        // 直接使用购物车数组的长度作为商品种类数量
        const itemTypeCount = cartItems.length;
        const cartCountElement = document.querySelector('.fa-shopping-bag').nextElementSibling;
        if (cartCountElement) {
            cartCountElement.textContent = itemTypeCount;
            // 如果数量大于0，显示数字
            cartCountElement.style.display = itemTypeCount > 0 ? 'flex' : 'none';
        }
    }

    function validateQuantity(input, event) {
        if (event) {
            event.stopPropagation();
        }
        let value = parseInt(input.value);
        if (isNaN(value) || value < 1) {
            input.value = 1;
        } else if (value > 99) {
            input.value = 99;
        }
    }

    function decreaseQuantity(event, productId) {
        event.stopPropagation();
        const input = document.getElementById(`quantity-${productId}`);
        let value = parseInt(input.value);
        if (value > 1) {
            input.value = value - 1;
        }
    }

    function increaseQuantity(event, productId) {
        event.stopPropagation();
        const input = document.getElementById(`quantity-${productId}`);
        let value = parseInt(input.value);
        if (value < 99) {
            input.value = value + 1;
        }
    }

    function showToast(message) {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.style.transform = 'translateY(0)';
        toast.style.opacity = '1';
        
        setTimeout(() => {
            toast.style.transform = 'translateY(-100%)';
            toast.style.opacity = '0';
        }, 3000);
    }

    function addToCart(event, productId) {
        event.stopPropagation();
        const quantity = parseInt(document.getElementById(`quantity-${productId}`).value);
        
        // 获取当前商品信息
        const productElement = event.target.closest('.group');
        const productInfo = {
            id: productId,
            title: productElement.querySelector('h3').textContent.trim(),
            price: parseFloat(productElement.querySelector('.text-gray-900').textContent.replace('¥', '')),
            mainPic: productElement.querySelector('img').src,
            quantity: quantity
        };

        // 获取现有购物车数据
        let cartItems = getCartItems();
        
        // 查找是否已存在该商品
        const existingItemIndex = cartItems.findIndex(item => item.id === productId);
        
        if (existingItemIndex > -1) {
            // 如果商品已存在，更新数量
            cartItems[existingItemIndex].quantity += quantity;
            // 确保不超过最大数量限制
            if (cartItems[existingItemIndex].quantity > 99) {
                cartItems[existingItemIndex].quantity = 99;
            }
        } else {
            // 如果商品不存在，添加新商品
            cartItems.push(productInfo);
        }

        // 保存更新后的购物车数据
        saveCartItems(cartItems);
        
        // 更新header中的购物车数量
        updateHeaderCartCount();

        // 显示提示信息
        showToast(`已成功添加${quantity}件商品到购物车`);
    }

    // 页面加载时初始化购物车数量
    document.addEventListener('DOMContentLoaded', function() {
        updateHeaderCartCount();
    });
</script>
